package com.fjwt.gz.service.activity.assign.acte022;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.bo.ActivityAwardAndSettingBo;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityDTO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.ActivityAwardService;
import com.fjwt.gz.service.impl.ActivitySettingService;
import com.fjwt.gz.service.impl.AwardSettingService;
import com.fjwt.gz.service.impl.SendAwardService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 定向派券活动------
 */
@Slf4j
@Service
public class ACTE022Service extends BaseActivityService<Object> {

    private static String logPrefix = "【定向派券活动】";
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private AwardSettingService awardSettingService;
    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private SendAwardService sendAwardService;

    /**
     * 新建活动
     */
    @Override
    public void add(BaseActivityDTO activityDTO) {
        log.info("新增ACTE022的活动");
        super.add(activityDTO);
    }

    /**
     * 修改活动
     */
    @Override
    public void update(BaseActivityDTO activityDTO) {
        log.info("更新ACTE022的活动");
        super.update(activityDTO);
    }

    /**
     * 删除活动
     */
    @Override
    public void delete(Long activityId) {
        log.info("删除ACTE022的活动");
        super.delete(activityId);
    }

    /**
     * 活动详情--pc
     */
    @Override
    public BaseActivityDTO detail(Long activityId) {
        log.info("查看ACTE022的活动详情");
        return super.detail(activityId);
    }

    /**
     * 参与活动
     */
    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("进入{}", logPrefix);
        super.takePartIn(fansActivityDTO);
        Long fansId = fansActivityDTO.getFansId();

        log.info("用户基本信息：{}", JSONUtil.toJsonStr(fansEntity));

        // 检测用户参与限制条件
        JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

        // 检测活动奖品配置
        List<ActivityAwardAndSettingBo> awardAndSettingBos = awardSettingService.getActivityAwardList(fansActivityDTO.getActivityId(), redisOutTime);
        // 校验用户奖品限制
        Map<Long, JSONObject> awardUserTimesJsonMap = new HashMap<>();
        for (ActivityAwardAndSettingBo activityAwardAndSettingBo : awardAndSettingBos) {
            JSONObject awardUserTimesJson = awardSettingService.AwardSettingRule(fansId, activityEntity.getAgentNo(), activityAwardAndSettingBo);
            if (ObjectUtils.isNotEmpty(awardUserTimesJson)) {
                awardUserTimesJsonMap.put(activityAwardAndSettingBo.getAwardId(), awardUserTimesJson);
            }
        }

        // 进行发券处理
        log.info("获取活动奖品返回的信息:{}", JSONUtil.toJsonStr(awardAndSettingBos));
        for (ActivityAwardAndSettingBo activityAwardAndSettingBo : awardAndSettingBos) {
            switch (activityAwardAndSettingBo.getAwardType()) {
                case Constants.AWARD.COUPON:
                    Long fansAwardId = sendAwardService.sendCouponOrGoods(fansId, fansActivityDTO.getAppId(), activityAwardAndSettingBo, activityEntity.getPayAuthId(),
                            fansActivityDTO.getActivityChannelId(), false, fansActivityDTO.getExtJson());
                    log.info("增加获奖记录返回的fansAwardId:{}", fansAwardId);
                    break;
                case Constants.AWARD.SCORE:
                    Long scoreValue = sendAwardService.sendScore(fansId, fansActivityDTO.getAppId(), activityAwardAndSettingBo, fansActivityDTO.getActivityChannelId(), false, fansActivityDTO.getAgentNo(), fansActivityDTO.getActivityId(), Constants.SCORE.ACTIVITY);
                    log.info("{}用户:{}增加{}福分", logPrefix, fansId, scoreValue);
                    break;
                default:
                    break;
            }
            JSONObject awardUserTimesJson = awardUserTimesJsonMap.get(activityAwardAndSettingBo.getAwardId());
            awardSettingService.updateAwardLimitCache(awardUserTimesJson, redisOutTime);
        }

        //重新放置活动奖品配置缓存
        if (!awardAndSettingBos.isEmpty()) {
            String activityAwardKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, fansActivityDTO.getActivityId(), Constants.REDIS_ACTIVITY.AWARD);
            RedisUtil.set(activityAwardKey, awardAndSettingBos, redisOutTime, TimeUnit.MILLISECONDS);
            log.info("活动奖品列表，修改奖品中的当前周期性领取次数数据，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(awardAndSettingBos), redisOutTime, "TimeUnit.MILLISECONDS");
        }

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimesBO = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimesBO)){
            activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
        }
        Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }

        return activityAwardService.toUserData(null);
    }
}
